package com.app.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * Context context 是全局的不要传Activity的引用过来，否则会内存泄露
 *
 */
public class DiskUser {
	
	
	private final static  String  DISK_NAME = "currentUser"; 
	public static void saveUserToDisk(String jsonUser,Context context) {
		FileOutputStream outStream=null;
		try {
			outStream = context.openFileOutput(DISK_NAME,Context.MODE_PRIVATE);
			outStream.write(jsonUser.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(outStream!=null)
				try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	
	/**
	 * 
	 * @param context
	 * @return
	 */
	public static String getUserFromDisk(Context context) {

		FileInputStream inStream=null;
		try {
			inStream = context.openFileInput(DISK_NAME);
			return readInStream(inStream);
		} catch (FileNotFoundException e) {
			return null;
		}
		finally{
			if(inStream!=null)
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

	}
	/**
	 * 
	 * @param inStream
	 * @return
	 */
	private static String readInStream(FileInputStream inStream) {
		ByteArrayOutputStream outStream=null;
		try {
		    outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length = -1;
			while ((length = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, length);
			}
			outStream.close();
			inStream.close();
			return outStream.toString();
		} catch (IOException e) {
		}finally{
			if(outStream!=null)try {outStream.close();} catch (IOException e) {
					e.printStackTrace();
				}
			if(inStream!=null)try {inStream.close();} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	public static void saveInfo(Context context, String key, List<Map<String, String>> datas) {
	    JSONArray mJsonArray = new JSONArray();
	    for (int i = 0; i < datas.size(); i++) {
	        Map<String, String> itemMap = datas.get(i);
	        Iterator<Entry<String, String>> iterator = itemMap.entrySet().iterator();
	 
	        JSONObject object = new JSONObject();
	 
	        while (iterator.hasNext()) {
	            Entry<String, String> entry = iterator.next();
	            try {
	                object.put(entry.getKey(), entry.getValue());
	            } catch (JSONException e) {
	 
	            }
	        }
	        mJsonArray.put(object);
	    }
	 
	    SharedPreferences sp = context.getSharedPreferences("localData", Context.MODE_PRIVATE);
	    Editor editor = sp.edit();
	    editor.putString(key, mJsonArray.toString());
	    editor.commit();
	}
	 
	public static List<Map<String, String>> getInfo(Context context, String key) {
	    List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
	    SharedPreferences sp = context.getSharedPreferences("localData", Context.MODE_PRIVATE);
	    String result = sp.getString(key, "");
	    try {
	        JSONArray array = new JSONArray(result);
	        for (int i = 0; i < array.length(); i++) {
	            JSONObject itemObject = array.getJSONObject(i);
	            Map<String, String> itemMap = new HashMap<String, String>();
	            JSONArray names = itemObject.names();
	            if (names != null) {
	                for (int j = 0; j < names.length(); j++) {
	                    String name = names.getString(j);
	                    String value = itemObject.getString(name);
	                    itemMap.put(name, value);
	                }
	            }
	            datas.add(itemMap);
	        }
	    } catch (JSONException e) {
	    	return null;
	    }
	 
	    return datas;
	}
	
	public static Map<String, String> ConvertObjToMap(Object obj) {
		Map<String, String> reMap = new HashMap<String, String>();
		if (obj == null)
			return null;
		Field[] fields = obj.getClass().getDeclaredFields();
		try {
			for (int i = 0; i < fields.length; i++) {
				try {
					Field f = obj.getClass().getDeclaredField(
							fields[i].getName());
					f.setAccessible(true);
					String o = (String)f.get(obj);
					reMap.put(fields[i].getName(), o);
				} catch (NoSuchFieldException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reMap;
	}
	
	public static String getUserInfoByKey(Context context, String key,String defult) {
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		if (sp != null) {
			return sp.getString(key, defult);
		}
		return defult;
	}
	
	public static String getUserInfoByKey(Context context, String key) {
		return getUserInfoByKey(context, key,"");
	}
	
	public static void setUserInfoByKey(Context context, String key, String value) {
		if(value == null) value ="" ;
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		if (sp != null) {
			Editor editor = sp.edit();
		    editor.putString(key, value);
		    editor.commit();
		}
	}
	
	public static void saveValueByKey(Context context, String key, Object value) {
		if(value == null) value ="" ;
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		if (sp != null) {
			Editor editor = sp.edit();
			if(value instanceof Long){
				editor.putLong(key, (long) value);
			}else if(value instanceof Integer){
				editor.putInt(key, (int) value);
			}else if(value instanceof String){
				editor.putString(key,(String) value);
			}else if(value instanceof Boolean){
				editor.putBoolean(key, (boolean) value);
			}else if(value instanceof Float){
				editor.putFloat(key, (float) value);
			}
		    editor.commit();
		}
	}
	
	
	public static long getLongValueByKey(Context context, String key){
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		return sp.getLong(key, 0);
	}
	
	public static int getIntValueByKey(Context context, String key){
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		return sp.getInt(key, 0);
	}
	
	public static String getStringValueByKey(Context context, String key){
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		return sp.getString(key, "");
	}
	
	public static boolean getBooleanValueByKey(Context context, String key,boolean defValue){
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		return sp.getBoolean(key, defValue);
	}
	
	
	public static void setSignOut(Context context) {
		SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		if (sp != null) {
			Editor editor = sp.edit();
			editor.putString("token", "");
			editor.putString("acount", "");
		    editor.commit();
		}
	}



	
}
